package com.illtamer.infinite.morii.config.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    @ExceptionHandler({Exception.class})
    public void handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error("Unexpected error", e);
        String xRequestedWith = request.getHeader("x-requested-with");
        // 判断是否是 Ajax 异步请求
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            response.setContentType("application/plain;charset=utf-8");
            try {
                response.getWriter().write("{status: 1, msg: \"服务端异常\"}");
            } catch (IOException io) {
                log.error("Connect error", io);
            }
        } else {
            response.setStatus(500);
        }
    }

}
